#!/bin/env python
# -*- coding: utf-8 -*-
# Filename:    main.py
# Revision:    1.0
# Date:        2012-06-14
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       simon-zzm@163.com
### END INIT INFO
from dbmodel import *
import tornado.web

class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        return self.get_secure_cookie("user")
    def check_user(self):
        _get_real_ip, _get_user_ip = get_clent_ip(self.request)
        _cookie_user_ip = self.current_user.split(",")[1]
        from time import time
        _get_now_unixtime = int(time())
        _access_timeout = self.get_secure_cookie("ttime")
        try:
            if (not self.current_user) or\
              (_get_now_unixtime > int(_access_timeout)) or \
              (_cookie_user_ip != _get_user_ip):
                self.clear_all_cookies()
                self.redirect("/")
                return
            else:
                return self.current_user.split(",")[0]
        except:
            self.clear_all_cookies()
            self.redirect("/")
            return

def get_clent_ip(_tmp):
    try:
        _get_user_ip = _tmp.remote_ip
    except:
        _get_user_ip = "Null"
    try:
        _get_real_ip =  _tmp.headers["X-Real-Ip"]
    except:
        _get_real_ip = "Null"
    return _get_real_ip, _get_user_ip

def if_get_domain_title():
    _get_global_info = get_global_set()[0]
    _get_domain = _get_global_info['domainname']
    _get_title = _get_global_info['title']
    return _get_domain, _get_title


def if_get_user_left_menu(user_name):
    _get_user_menu_id = get_left_menu_id(user_name)[0]['manage_menu']
    _get_user_left_menu_list = get_left_menu_list(_get_user_menu_id)
    return _get_user_left_menu_list


def if_get_user_project(user_name):
    _get_manage_project_list = get_manage_project(user_name)[0]['manage_project']
    _get_user_project_list = get_user_project_list(_get_manage_project_list)
    return _get_user_project_list


def if_get_project_id(project_name):
    return odb_project_id(project_name)


def if_context_page(_domain, \
                    _title, \
                    _get_user_left_menu, \
                    _context):
    self.render("templates/mycontext.html", domain=_domain, \
                 title=_title, items=_get_user_left_menu, \
                 error_context=_context)


from binascii import b2a_hex, a2b_hex
from Crypto.Cipher import DES
from config import *
def if_pass_encryption(pass_context):
    obj = DES.new(pass_key)
    _pass = pass_context + ' ' * (40 - len(pass_context))
    print len(_pass)
    cryp = obj.encrypt(_pass)
    return b2a_hex(cryp) 

def if_pass_decryption(pass_context):
    from string import strip
    obj = DES.new(pass_key)
    get_cryp = a2b_hex(pass_context)
    after_text = strip(obj.decrypt(get_cryp))
    return after_text 
